import math
import matplotlib.pyplot as plt
import torch
from torch import nn
from torch.nn import functional as F
from d2l import torch as d2l
from rnn_data_load import load_data_time_machine
from custom import train_ch8


# @save
class RNNModel(nn.Module):
    """循环神经网络模型"""

    def __init__(self, rnn_layer, vocab_size, **kwargs):
        super(RNNModel, self).__init__(**kwargs)
        self.rnn = rnn_layer
        self.vocab_size = vocab_size
        self.num_hiddens = self.rnn.hidden_size
        # 如果RNN是双向的（之后将介绍），num_directions应该是2，否则应该是1
        if not self.rnn.bidirectional:
            self.num_directions = 1
            self.linear = nn.Linear(self.num_hiddens, self.vocab_size)
        else:
            self.num_directions = 2
            self.linear = nn.Linear(self.num_hiddens * 2, self.vocab_size)

    def forward(self, inputs, state):
        X = F.one_hot(inputs.T.long(), self.vocab_size)
        X = X.to(torch.float32)
        # print(X.shape,"X")
        # [28, 32, 932] T = 28  N = 32  D = 932
        # 时间步数*批量大小,词表大小
        # Y [28, 32, 512] T = 28  N = 32  D = 512
        Y, state = self.rnn(X, state)
        # torch.Size([T, N, D]) torch.Size([T, N, H]) torch.Size([1, N, H])
        # print("X.shape,Y.shape,state.shape",X.shape,Y.shape,state.shape)  #state.shape= [2, 32, 256]
        # 全连接层首先将Y的形状改为(时间步数*批量大小,隐藏单元数)
        # 它的输出形状是(时间步数*批量大小,词表大小)。
        # torch.Size([28, 32, 256]) torch.Size([28*32, 256])
        output = self.linear(Y.reshape((-1, Y.shape[-1])))
        return output, state

    def begin_state(self, device, batch_size=1):
        if not isinstance(self.rnn, nn.LSTM):
            # nn.GRU以张量作为隐状态
            return torch.zeros((self.num_directions * self.rnn.num_layers,
                                batch_size, self.num_hiddens),
                               device=device)
        else:
            # nn.LSTM以元组作为隐状态
            return (torch.zeros((
                self.num_directions * self.rnn.num_layers,
                batch_size, self.num_hiddens), device=device),
                    torch.zeros((
                        self.num_directions * self.rnn.num_layers,
                        batch_size, self.num_hiddens), device=device))


# 加载之前准备好的数据
batch_size, num_steps = 32, 28
train_iter, vocab = load_data_time_machine(batch_size, num_steps)
num_hiddens = 256
rnn_layer = nn.RNN(len(vocab), num_hiddens, bidirectional=False)
# [1, 32, 256] H  如果是双向则 最前面的是2
state = torch.zeros((1, batch_size, num_hiddens))
print("state", state.shape)
X = torch.rand(size=(num_steps, batch_size, len(vocab)))
Y, state_new = rnn_layer(X, state)
# Y, state_new torch.Size([28, 32, 256]) torch.Size([1, 32, 256])
# print("Y, state_new", Y.shape, state_new.shape)

device = d2l.try_gpu()
net = RNNModel(rnn_layer, vocab_size=len(vocab))
net = net.to(device)
num_epochs, lr = 200, 1
train_ch8(net, train_iter, vocab, lr, num_epochs, device)
plt.show()
"""
对于RNN网络把握一下几点
1、输入是 [t,n,d] 的.
2、H 初始设定是 [1,n,h] 如果是双向网络则为  [2,n,h].
3、X将循环输入到网络，重新计算H和输出。输出是 Y [t,n,h] 的，H 最终得到一个  [1,n,h] 矩阵且是一个不断得带更新的产物.
"""
